<template>
  <el-dialog :visible.sync="visibleSelect"
             width="768px"
             :append-to-body="true"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <div slot="title">
      {{$t('tenant.switch')}}<view-linked-info :linkKey="'SwitchClient'"></view-linked-info>
    </div>
    <el-form :model="dataForm"
             :inline="false"
             ref="dataForm"
             v-loading="loading"
             label-position="top">
      <el-form-item prop="tenantCode"
                    :label="$t('custom.dataset.tenantCode')">
        <el-row>
          <el-col :span="7">
            <select-client-id ref="selectClientId"
                              v-model="dataForm.tenantCode"
                              :isChangeClient="true"
                              :width="96"
                              @changeClient="clientChange"
                              :isShowCreate="true"></select-client-id>
          </el-col>
          <el-col :span="4">
            <div v-loading='datasetLayerSelectLoading'>
              <!-- <el-button @click="changeLayerStatus"
                           v-if="useLayerStatus"
                           class="cuifont icon_dataset_add_layer"
                           type="mini"
                           style="font-size:14px;padding:7px"></el-button> -->
              <el-select v-model="datasetLayerId"
                         @change="onLayerChange"
                         placeholder="Please Select Layer"
                         clearable
                         style="height:30px;">
                <el-option v-for="(item,index) in layerTempList"
                           :label="item.name"
                           :key="index"
                           :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4"
                  style="margin-left:8px;">
            <el-button size="mini"
                       type="primary"
                       @click="commitHandle(dataForm)">Switch To Client</el-button>
          </el-col>
          <el-col :span="4"
                  style="margin-left:3px;">
            <el-button size="mini"
                       type="primary"
                       @click="switchToDefault()">Switch To Default</el-button>
          </el-col>
          <el-col :span="4"
                  style="padding-left:10px;">
            <el-button size="mini"
                       type="primary"
                       @click="switchToMySelf()">Switch To Myself</el-button>
          </el-col>
        </el-row>
        <el-row v-if="dataForm.tenantCode">
          <el-col :span="9">
            Client Code : {{dataForm.tenantCode}}
          </el-col>
          <el-col :span="15">
            WebSite :
            <el-link :underline="false"
                     type="primary"
                     @click="clickLink"
                     target="_blank">{{dataForm.website?dataForm.website:'https://'+dataForm.tenantName}}</el-link>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item class="switch-user-grid">
        <el-tabs v-model="activeName">
          <el-tab-pane label="User"
                       name="first">
            <ejs-grid :dataSource="userListData"
                      v-loading='dataListLoading'
                      :allowResizing="gridDefaultSetting.allowResizing"
                      :allowFiltering="gridDefaultSetting.allowFiltering"
                      :filterSettings="gridDefaultSetting.filterSettings"
                      :allowGrouping="gridDefaultSetting.allowGrouping"
                      :allowPaging="gridDefaultSetting.allowPaging"
                      :toolbar="gridDefaultSetting.toolbar"
                      :showColumnChooser="gridDefaultSetting.showColumnChooser"
                      :allowReordering="gridDefaultSetting.allowReordering"
                      :allowSorting="gridDefaultSetting.allowSorting"
                      ref="switch-user-grid"
                      :height="200"
                      :selectionSettings="gridDefaultSetting.selectOptions"
                      :commandClick="commandClick"
                      :pageSettings="userPageSettings"
                      :showColumnMenu='gridDefaultSetting.showColumnMenu'
                      :sortSettings="sortuserSettings">
              <e-columns>
                <!-- <e-column field="realName"
                                headerText="User Name"
                                clipMode='EllipsisWithTooltip'
                                :width="120"
                                ></e-column> -->
                <e-column field="username"
                          clipMode='EllipsisWithTooltip'
                          headerText="Email"
                          :width="150"></e-column>
                <e-column field="roleString"
                          headerText="Role Name"
                          clipMode='EllipsisWithTooltip'
                          :width="150"></e-column>
                <e-column field="tenantTimezone"
                          headerText="TimeZone"
                          clipMode='EllipsisWithTooltip'
                          :width="180"></e-column>
                <!-- <e-column field="timezoneOffset"
                                headerText="Offset"
                                clipMode='EllipsisWithTooltip'
                                :width="80"></e-column> -->
                <e-column :template="UsersBtn"
                          :width='100'
                          textAlign='Right'></e-column>
              </e-columns>
            </ejs-grid>
          </el-tab-pane>
          <el-tab-pane label="Role"
                       name="second">
            <ejs-grid :dataSource="roleListData"
                      v-loading='dataListLoading'
                      :allowResizing="gridDefaultSetting.allowResizing"
                      :allowFiltering="gridDefaultSetting.allowFiltering"
                      :filterSettings="gridDefaultSetting.filterSettings"
                      :allowGrouping="gridDefaultSetting.allowGrouping"
                      :allowPaging="gridDefaultSetting.allowPaging"
                      :toolbar="gridDefaultSetting.toolbar"
                      :showColumnChooser="gridDefaultSetting.showColumnChooser"
                      :allowReordering="gridDefaultSetting.allowReordering"
                      :allowSorting="gridDefaultSetting.allowSorting"
                      ref="switch-role-grid"
                      height="220px"
                      :selectionSettings="gridDefaultSetting.selectOptions"
                      :commandClick="commandClickRole"
                      :pageSettings="rolePageSettings"
                      :showColumnMenu='gridDefaultSetting.showColumnMenu'
                      :sortSettings="sortroleSettings">
              <e-columns>
                <e-column field="name"
                          headerText="Name"
                          :width="150"></e-column>
                <e-column field="remark"
                          headerText="Remark"
                          clipMode='EllipsisWithTooltip'
                          :width="150"></e-column>
                <e-column :template="RolesBtn"
                          :width='100'
                          textAlign='Right'></e-column>
              </e-columns>
            </ejs-grid>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
    </el-form>
    <z-notice :visible.sync="showNotice"
              v-bind="noticeObject"></z-notice>
    <template slot="footer">
      <el-button type="default"
                 @click="cancelHandle()"
                 size="mini">{{ $t('cancel') }}</el-button>
      <!-- <el-button type="primary"
                 @click="commitHandle()"
                 size="mini">{{ $t('confirm') }}</el-button> -->
    </template>
  </el-dialog>
</template>

<script>
import Vue from 'vue'
import Cookies from 'js-cookie'
import mixinViewModule from '@/mixins/view-module'
import selectClientId from '../components/select-client-id/src/select-client-id.vue'
import ZNotice from '@/components/storybook/z-dialog-notice'
export default {
  components: { selectClientId, ZNotice },
  mixins: [mixinViewModule],
  data () {
    return {
      showNotice: false,
      noticeObject: {
        icon: 'icon_message-alt-error',
        title: 'Grant access is required before you can access the tenant.',
        okButton: {
          text: 'OK',
          type: 'primary'
        }
      },
      layerTempList: [],
      datasetLayerId: null,
      datasetLayerSelectLoading: false,
      useLayerStatus: true,
      visibleSelect: false,
      currentRow: null,
      mixinViewModuleOptions: {
        // getDataListURL: '/web/um/sys/tenant/page',
        // getDataListIsPage: true,
        createdIsNeed: false
      },
      dataForm: {
        tenantCode: '',
        tenantName: '',
        website: ''
      },
      activeName: 'first',
      userListData: [],
      roleListData: [],
      gridDefaultSetting: {
        allowResizing: true,
        allowFiltering: false,
        showColumnMenu: false,
        filterSettings: { type: 'Excel' },
        allowGrouping: false,
        allowPaging: true,
        toolbar: ['Search', 'ColumnChooser'],
        allowExcelExport: true,
        allowPdfExport: true,
        showColumnChooser: true,
        groupOptions: { columns: ['name'] },
        allowReordering: true,
        allowSorting: true,
        allowTextWrap: true,
        height: window.innerHeight - 230,
        selectOptions: { type: 'Multiple' },
        groupSettings: {
          allowReordering: false,
          columns: [],
          disablePageWiseAggregates: false,
          enableLazyLoading: false,
          showDropArea: true,
          showGroupedColumn: false,
          showToggleButton: false
        }
      },
      userPageSettings: { pageSize: 20, pageSizes: [20, 50, 100, 200], pageCount: 4 },
      rolePageSettings: { pageSize: 10, pageSizes: [10, 20, 50, 100], pageCount: 4 },
      loading: false,
      UsersBtn: function () {
        return { template: UsersBtn }
      },
      RolesBtn: function () {
        return { template: RolesBtn }
      },
      dataListLoading: false,
      sortroleSettings: {
        columns: [
          { field: 'name', direction: 'Ascending' }
        ]
      },
      sortuserSettings: {
        columns: [
          { field: 'roleString', direction: 'Ascending' }
        ]
      }
    }
  },

  created () {
    Vue['_this_switch_client'] = this
    this.getLayerList()
  },
  methods: {
    async toggleTenant () {
      const params = {
        tenantCode: this.dataForm.tenantCode
      }
      const { data } = await this.$interface.login.toggleTenant(params)
      if (data.code === 0) {
        if (!data.data) {
          this.showNotice = true
        }
        return data.data
      } else {
        this.$message.error(data.msg)
      }
    },
    onLayerChange (datasetLayerId) {
      sessionStorage.setItem('clientLayerId', datasetLayerId)
      if (this.$refs.selectClientId) {
        this.$refs.selectClientId.getClientList(datasetLayerId)
      }
    },
    getLayerList () {
      this.datasetLayerSelectLoading = true
      var params = {
        datasetKey: 'sys_tenant_list'
      }
      this.$interface.reports.getDrillThroughDataInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.layerTempList = res.data
        this.datasetLayerId = res.data[0].id
        if (sessionStorage.getItem('clientLayerId')) {
          this.datasetLayerId = sessionStorage.getItem('clientLayerId')
        }
        if (this.$refs.selectClientId) {
          this.$refs.selectClientId.getClientList(this.datasetLayerId)
        }
        this.datasetLayerSelectLoading = false
      }).catch(() => { this.datasetLayerSelectLoading = false })
    },
    changeLayerStatus () {
      this.useLayerStatus = !this.useLayerStatus
    },
    init () {
      this.visibleSelect = true
      this.$nextTick(() => {
        // this.getUserList()
        // this.getRoleList()
      })
    },
    cancelHandle () {
      this.visibleSelect = false
    },
    async commitHandle (data) {
      this.visibleSelect = false
      const bol = await this.toggleTenant()
      if (!bol) return false
      this.initNextFilter()
      if (data && !data.tenantCode) {
        return this.$message.error(this.$t('tenant.select'))
      } else {
        window.location.protocol === 'https:'?  Cookies.set('tenant_code', data.tenantCode, { sameSite: 'None', secure: true }) : Cookies.set('tenant_code', data.tenantCode)
        if (data.loginAsUserId) {
          if (sessionStorage.getItem('loginAsRoleId')) {
            sessionStorage.removeItem('loginAsRoleId')
          }
          sessionStorage.setItem('loginAsUserId', data.loginAsUserId)
        } else {
          sessionStorage.removeItem('loginAsUserId')
        }
        if (data.loginAsRoleId) {
          if (sessionStorage.getItem('loginAsUserId')) {
            sessionStorage.removeItem('loginAsUserId')
          }
          sessionStorage.setItem('loginAsRoleId', data.loginAsRoleId)
        }
        if (sessionStorage.getItem('isMySelfCode') === data.tenantCode) {
          sessionStorage.setItem('isSwitchTenant', 0)
          this.$store.dispatch('setIsSwitchTenant', 0)
        } else {
          sessionStorage.setItem('isSwitchTenant', 1)
          this.$store.dispatch('setIsSwitchTenant', 1)
        }
        this.$store.dispatch('setTenantName', data.tenantName)
        this.$store.dispatch('setTenantCode', data.tenantCode)
        this.clearLocal()
        this.$store.state.contentTabs = []
        this.$router.push({ name: 'home' }).then(() => {
          window.location.reload()
        }).catch(() => {
          window.location.reload()
        })


      }
    },
    commandClick (type, row) {
      if (!this.dataForm.tenantCode) {
        return this.$message.error(this.$t('tenant.select'))
      }
      if (type === 'User') {
        const userLoginAs = {
          loginAsUserId: row.id,
          ...this.dataForm
        }
        this.commitHandle(userLoginAs)
      }
    },
    commandClickRole (type, row) {
      if (!this.dataForm.tenantCode) {
        return this.$message.error(this.$t('tenant.select'))
      }
      if (type === 'Role') {
        const roleLoginAs = {
          loginAsRoleId: row.roleId,
          ...this.dataForm
        }
        this.commitHandle(roleLoginAs)
      }
    },
    initNextFilter () {
      this.$store.commit('AUTONEXTTICKETFILTERID', '')
      this.$store.commit('NEXTTICKETFILTERID', '')
    },
    switchToDefault () {
      this.visibleSelect = false
      this.initNextFilter()
      window.location.protocol === 'https:'? Cookies.set('tenant_code', 1001, { sameSite: 'None', secure: true }) :  Cookies.set('tenant_code', 1001)
      if (sessionStorage.getItem('isSwitchTenant')) {
        sessionStorage.removeItem('isSwitchTenant')
        this.$store.dispatch('setIsSwitchTenant', 0)
      }
      if (sessionStorage.getItem('loginAsRoleId')) {
        sessionStorage.removeItem('loginAsRoleId')
      }
      if (sessionStorage.getItem('loginAsUserId')) {
        sessionStorage.removeItem('loginAsUserId')
      }
      sessionStorage.setItem('isSwitchTenant', 1)
      this.$store.dispatch('SET_IS_SWITCH_TENANT', 1)
      this.$store.dispatch('setTenantName', 'default')
      this.$store.dispatch('setTenantCode', 1001)
      this.clearLocal()
      this.$store.state.contentTabs = []
      this.$router.push({ name: 'home' })
      window.location.reload()
    },
    clientChange (data) {
      if (data) {
        this.dataListLoading = true
        this.dataForm.tenantName = data.tenantName
        this.dataForm.tenantCode = data.tenantCode
        this.dataForm.website = data.website
        this.$nextTick(() => {
          this.getRoleList(data)
          this.getUserList(data)
        })
      } else {
        this.roleListData = []
        this.userListData = []
        this.dataForm = {
          tenantCode: '',
          tenantName: '',
          website: ''
        }
      }
    },
    getUserList (data) {
      const params = {
        status: 1
      }
      this.userListData = []
      if (data) {
        params.tenantCode = data.tenantCode
      } else {
        return
      }
      this.$interface.schedule.getWorkScheduledUserListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (Array.isArray(res.data) && res.data.length > 0) {
            for (let index = 0; index < res.data.length; index++) {
              const element = res.data[index]
              element.tenantTimezone = element.timezoneId + '(' + element.timezoneName + ')'
              element.roleList = this._.sortBy(element.roleList, function (item) {
                return item
              })
              element.roleString = element.roleList.join(',')
            }
          }
          this.userListData = res.data
          this.dataListLoading = false
        })
    },
    getRoleList (data) {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.roleListData = []
      if (data) {
        params.tenantCode = data.tenantCode
      } else {
        return
      }
      this.$interface.system.getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleListData = res.data
          this.dataListLoading = false
        }).catch(() => { })
    },
    switchToMySelf () {
      this.visibleSelect = false
      this.initNextFilter()
      if (window.location.hostname === 'localhost') {
        return this.$message.error("DEV server no't use this function")
      }
      window.location.protocol === 'https:'? Cookies.set('tenant_code', sessionStorage.getItem('isMySelfCode'), { sameSite: 'None', secure: true }) : Cookies.set('tenant_code', sessionStorage.getItem('isMySelfCode'))
      if (sessionStorage.getItem('loginAsRoleId')) {
        sessionStorage.removeItem('loginAsRoleId')
      }
      if (sessionStorage.getItem('loginAsUserId')) {
        sessionStorage.removeItem('loginAsUserId')
      }
      sessionStorage.setItem('isSwitchTenant', 0)
      this.$store.dispatch('setIsSwitchTenant', 0)
      this.$store.dispatch('setTenantName', 'mspbots.ai')
      var tenantCode = ''
      if (window.location.hostname === 'app.maibozhineng.com') {
        tenantCode = '1285403951449878530'
      } else {
        tenantCode = '1285404348503920642'
      }
      window.location.protocol === 'https:'? Cookies.set('tenant_code', tenantCode, { sameSite: 'None', secure: true }) :  Cookies.set('tenant_code', tenantCode)
      this.$store.dispatch('setTenantCode', tenantCode)
      this.clearLocal()
      this.$store.state.contentTabs = []
      this.$router.push({ name: 'home' }).then(() => {
          window.location.reload()
        }).catch(() => {
          window.location.reload()
        })
    },
    clearLocal () {
      localStorage.clear()
    },
    clickLink () {
      var link = ''
      if (this.dataForm) {
        link = this.dataForm.website ? 'https://' + this.dataForm.website : 'https://' + this.dataForm.tenantName
      } else {
        return this.$message.error('No WebSite')
      }
      window.open(link, '_blank')
    }

  },
  beforeDestroy () {
    delete Vue['_this_switch_client']
  }
}
const UsersBtn = Vue.component(
  'users-btn', {
  template: `<div style="display: flex;justify-content: flex-end;">
      <el-button size="mini" plain type="primary" @click="clickSelect('User',$data.data)">Switch to User</el-button>
    </div>`,
  data () {
    return {}
  },
  methods: {
    clickSelect (e, row) {
      Vue._this_switch_client.commandClick(e, row)
    }
  }
}
)
const RolesBtn = Vue.component(
  'roles-btn', {
  template: `<div style="display: flex;justify-content: flex-end;">
      <el-button size="mini" plain type="primary" @click="clickSelectRole('Role',$data.data)">Switch to Role</el-button>
    </div>`,
  data () {
    return {}
  },
  methods: {
    clickSelectRole (e, row) {
      Vue._this_switch_client.commandClickRole(e, row)
    }
  }
}
)
</script>

<style lang="scss">
.aui-wrapper {
  .el-table th {
    background-color: #ffffff;
  }
}
.switch-user-grid {
  .e-grid .e-content {
    height: 25vh !important;
  }
}
</style>
